package com.example.demo.api.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.api.config.R;
import com.example.demo.api.db.pojo.TableUser;
import com.example.demo.api.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody @Valid LoginForm form){
        //验证信息打包获得微信开发者工具的访问许可
        String code = form.getCode();
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap param = new HashMap();
        param.put("appid","wx14adf005643d661c");
        param.put("secret","0ff24574f840a7d950e5c628278188b5");
        param.put("js_code",code);
        param.put("grant_type","authorization_code");
        String resp = HttpUtil.post(url,param);
        JSONObject json = JSONUtil.parseObj(resp);
        String openId = json.getStr("openid");
        if(openId == null || openId.length()==0){
            throw new RuntimeException("openId获取失败");

        }

        //登录或注册
        TableUser user = new TableUser();
        user.setNickname(form.getNickname());
        System.out.print("nickname\n");
        user.setSex(form.getSex());
        System.out.print("sex\n");
        user.setTel(form.getTel());
        System.out.print("tel\n");
        user.setOpenId(openId);
//        System.out.print("getDate\n");
//        try {
//            DateTime date=new DateTime();
//            user.setCreateTime(date);
//            System.out.print(date.toDateStr()+"\n");
//        }catch (Exception e){
//            e.printStackTrace();
//        }
        System.out.print("id\n");
        Long id = userService.login(user);
        StpUtil.login(id);
        System.out.print("id_over\n");
        String token = StpUtil.getTokenInfo().getTokenValue();
        return R.ok().put("token",token);

        }

    @PostMapping("/searchUserLocation")
    @SaCheckLogin
    public R searchUserLocation(@RequestBody @Valid SearchUserLocationForm form) throws Exception{
        String startDate = new DateTime().offset(DateField.DAY_OF_MONTH,14).toDateStr();
        String endDate = new DateTime().toDateStr();
        String result = userService.searchUserLocation(form.getTel(),startDate,endDate);
        return R.ok().put("result",result);
    }
}
